package ru.smc.hogwarts.servlets.subjects;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Person;
import ru.smc.hogwarts.model.Subject;

public class SubjectsAdd extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String error = "";
	private int professor = 0;
	private String name = null;
	private int auditorium = 0;
	private int year = 0;
	private String type = null;
	private HttpSession session;
       
    public SubjectsAdd() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("error", error);

		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
    	
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
    	
    	String select = "select p " +
			"from Person p " +
			"where (p.role.name = 'professor' " +
			"or p.role.name = 'head' " +
			"or p.role.name = 'head_house') " +
			"and p.id not in (select s.professor.id from Subject s)";
		
		List<Person> professors = em.createQuery(select).getResultList();
		request.setAttribute("professors", professors);
		
		em.close();
		
		if (error == "") {
			professor = 0;
			name = null;
			auditorium = 0;
			year = 0;
			type = null;	
		}
		
		request.setAttribute("professor", professor);
		request.setAttribute("name", name);
		request.setAttribute("auditorium", auditorium);
		request.setAttribute("year", year);
		request.setAttribute("type", type);
		
		error = "";
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/pages/subjects/subjectAdd.jsp");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		error = "";
		
		try {
			name = request.getParameter("name");
			if (name == "") 
				error += "<span>П</span>оле \"Название\" не должно быть пустым.<br>";

			if (request.getParameter("auditorium") == "") {
				error += "<span>П</span>оле \"Аудитория\" не должно быть пустым.<br>";
			} else {
				if (request.getParameter("auditorium").matches("^[0-9]+$")) {
					auditorium = Integer.parseInt(request.getParameter("auditorium"));
				} else {
					error += "<span>П</span>оле \"Аудитория\" должно содержать цифры.<br>";
				}				
			}

			if (request.getParameter("year") == "") {
				error += "<span>П</span>оле \"Курс\" не должно быть пустым.<br>";
			} else {
				year = Integer.parseInt(request.getParameter("year"));
			}
			
			type = request.getParameter("type");
			if (type == "") 
				error += "<span>П</span>оле \"Тип\" не должно быть пустым.<br>";
			
			if (request.getParameter("professor") == "") {
				error += "<span>П</span>оле \"Профессор\" не должно быть пустым. " +
						"Если в списке нет вариантов выбора, значит для всех профессоров выбраны дисциплины. " +
						"<a href=\"professors/add\"><span>Добавьте нового профессора</span>.</a><br>";
			} else {
				professor = Integer.parseInt(request.getParameter("professor"));
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		if (error == "") { 
			this.addSubject(professor, name, auditorium, year, type);
			response.sendRedirect(request.getContextPath() + "/subjects");
		} else if (error != "") {
			response.sendRedirect(request.getContextPath() + "/subjects/add");
		}
	}
	
	private void addSubject(int professor, String name, 
			int auditorium, int year, String type) {
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		Person _professor = em.find(Person.class, professor);;
		
		Subject subject = new Subject();
		
		subject.setProfessor(_professor);
		subject.setName(name);
		subject.setAuditorium(auditorium);
		subject.setYear(year);
		subject.setType(type);
		
		em.persist(subject);
		em.getTransaction().commit();
				
		em.close();
	}

}
